package com.yuan.view;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  统一响应视图,Jason格式
 * </p>
 *
 * @author asuyuan
 * @since 2023/2/7
 */
@Data
public class YuancityView {
    public static final String MEDIA_JSON_TYPE = "application/json;charset=utf-8";
    @ApiModelProperty(value = "返回状态码")
    private Integer code; //响应编码,200:成功,400:失败
    @ApiModelProperty(value = "是否成功")
    private  Boolean success;//是否成功
    @ApiModelProperty(value = "返回消息")
    private String message;//返回消息
    @ApiModelProperty(value = "返回数据")
    private Map<String,Object> content =new HashMap<String, Object>() ;//返回数据

    public static YuancityView success(String message){
        YuancityView yuancityView = new YuancityView();
        yuancityView.setCode(200);
        yuancityView.setSuccess(true);
        yuancityView.setMessage(message);
        return yuancityView;
    }
    public static YuancityView failure(String message){
        YuancityView yuancityView = new YuancityView();
        yuancityView.setCode(400);
        yuancityView.setSuccess(false);
        yuancityView.setMessage(message);
        return yuancityView;
    }
    public static YuancityView failure(String message,Integer code){
        YuancityView yuancityView = new YuancityView();
        yuancityView.setCode(code);
        yuancityView.setSuccess(false);
        yuancityView.setMessage(message);
        return yuancityView;
    }


    public YuancityView put(String key,Object value){
        content.put(key, value);
        return this;
    }
    public void responseWebClient(HttpServletResponse response) {
        response.setContentType(MEDIA_JSON_TYPE);

        try {
            PrintWriter writer = response.getWriter();
            writer.write(JsonHelper.toJSON(this));
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        YuancityView view = YuancityView.success("注册成功").put("username", "基尼太美");
        String json = JsonHelper.toJSON(view);
        System.out.println("json = " + json);
    }

}
